﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace ImTag.Silverlight
{
    public partial class SearchBar : UserControl
    {
        public SearchBar()
        {
            InitializeComponent();
            this.TaglessButton.Click += (source, ev) =>
            {
                var service = new ImTagService.ImTagServiceSoapClient();
                service.LoadTaglessImagesCompleted += (source2, ev2) =>
                {
                    if (ev2.Result != null)
                        MainPage.Current.SearchResultPanel.Result = ev2.Result.Select(image => new Thumbnail() { ImagePath = image.ImagePath, Tags = image.Tags });
                };
                service.LoadTaglessImagesAsync();
                this.AvailableTags = TagsManager.AvailableTags;
                this.SearchTags = new string[0];
            };
        }

        public void PerformSearch()
        {
            var service = new ImTagService.ImTagServiceSoapClient();
            service.SearchImagesCompleted += (source2, ev2) =>
            {
                if (ev2.Result != null)
                    MainPage.Current.SearchResultPanel.Result = ev2.Result.Select(image => new Thumbnail() { ImagePath = image.ImagePath, Tags = image.Tags });
                var temp1 = ev2.Result.SelectMany(image => image.Tags ?? new ImTagService.ArrayOfString()).ToArray();
                var temp11 = temp1.Distinct().ToArray();
                var temp2 = temp11.Except(this.SearchTags).ToArray();
                this.AvailableTags = temp2;
            };

            service.SearchImagesAsync(this.SearchTags.To<ImTagService.ArrayOfString>());
            
        }
        
        private IEnumerable<string> availableTags;
        public IEnumerable<string> AvailableTags
        {
            get{ return this.availableTags;}
            set
            {
                this.availableTags = value;
                this.AvailableTagsPanel.Children.Clear();
                foreach (var tag in value)
                    this.AvailableTagsPanel.Children.Add(new Tag() { TagText = tag });
            }
        }
        private IEnumerable<string> searchTags;
        public IEnumerable<string> SearchTags
        {
            get { return this.searchTags; }
            set
            {
                this.searchTags = value;
                this.SearchedTagsPanel.Children.Clear();
                foreach (var tag in value)
                    this.SearchedTagsPanel.Children.Add(new Tag() { TagText = tag });
            }
        }
    }
}
